package it.cst.util;

import it.cst.entity.Group;
import it.cst.entity.Match;
import it.cst.entity.Player;
import it.cst.entity.User;
import it.cst.entity.controller.MatchController;
import it.cst.entity.service.RoleService;
import it.cst.entity.service.UserService;

import it.intext.gmail.application.GMailSender;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class Utils {
	private static final Logger logger = LoggerFactory.getLogger(Utils.class);
	@Autowired
	private UserService userService;

	public Utils(UserService userService){
		this.userService = userService;
	}
	
	
	public static Date getDateFromJQMPicker(String date){
		Calendar cal = Calendar.getInstance();
	    cal.set(Calendar.YEAR, Integer.parseInt(date.substring(0,4)));
	    cal.set(Calendar.MONTH, Integer.parseInt(date.substring(5,7))-1);
	    cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date.substring(8,10)));
	    Date ret = cal.getTime();
	    return ret;
	}
	
	
	
	public static void sendNotify(List<User> userList, User currentUser,Match match, String action) {
		RoleService ros = (RoleService) SpringApplicationContext.getBean("roleService");
		Roles roles = Roles.getInstance(ros);
		User urd = null;
		User ura = null;
		User ubd = null;
		User uba = null;
		int rs = 0; 
		int bs = 0;
		for(Group g : match.getGroups()) {
			if(g.getColor().equalsIgnoreCase(MatchController.RED_COLOR)){
				rs = g.getScore();
				for(Player p : g.getPlayers()){
					if(p.getIdrole().compareTo(roles.getRole(Roles.DEFENSE_ROLE_NAME).getId()) == 0){
						urd=p.getUser();
					}
					else{
						ura = p.getUser();
					}
				}
			}
			else
			{
				bs = g.getScore();
				for(Player p : g.getPlayers()){
					if(p.getIdrole().compareTo(roles.getRole(Roles.DEFENSE_ROLE_NAME).getId()) == 0){
						ubd=p.getUser();
					}
					else{
						uba = p.getUser();
					}
				}
			}		
		}
		for(User u : userList){
			if(u.getNotify() && u.getEmail() != null && !u.getEmail().isEmpty()){
				StringBuffer body = new StringBuffer();
				String pattern = "yyyy-MM-dd hh:mm:ss";
				SimpleDateFormat sdf = new SimpleDateFormat(pattern);
				if(action.equalsIgnoreCase("insertMatch")){
					body.append("<p>L'utente " + currentUser.getFirstname() + " " + currentUser.getLastname() + " in data " + sdf.format(match.getTimestamp()) + " ha inserito il seguente risultato : </p>");
				}
				else if(action.equalsIgnoreCase("deleteMatch")){
					body.append("<p>L'utente " + currentUser.getFirstname() + " " + currentUser.getLastname() + " in data " + sdf.format(match.getTimestamp()) + " ha eliminato il seguente risultato : </p>");					
				}
				body.append("<p></p>");
				body.append("<hr/>");
				body.append("<table style=\"border-collapse:collapse\">");
				body.append("<tr bgcolor=\"red\">");
				body.append("<td>");
				body.append("<b>Difensore : </b>");
				body.append("</td>");
				body.append("<td>");
				body.append("<b>" + urd.getFirstname() + " " + urd.getLastname() +"</b>");
				body.append("</td>");
				body.append("</tr>");
				body.append("<tr bgcolor=\"red\">");
				body.append("<td>");
				body.append("<b>Attaccante : </b>");
				body.append("</td>");
				body.append("<td>");
				body.append("<b>" + ura.getFirstname() + " " + ura.getLastname() +"</b>");
				body.append("</td>");
				body.append("</tr>");
				body.append("<tr bgcolor=\"red\">");
				body.append("<td>");
				body.append("<b>Punteggio : </b>");
				body.append("</td>");
				body.append("<td>");
				body.append("<b>" + rs +"</b>");
				body.append("</td>");
				body.append("</tr>");
				body.append("<tr bgcolor=\"blue\" >");
				body.append("<td>");
				body.append("<font color=\"white\"><b>Difensore : </b></font>");
				body.append("</td>");
				body.append("<td>");
				body.append("<font color=\"white\"><b>" + ubd.getFirstname() + " " + ubd.getLastname() +"</b></font>");
				body.append("</td>");
				body.append("</tr>");
				body.append("<tr bgcolor=\"blue\">");
				body.append("<td>");
				body.append("<font color=\"white\"><b>Attaccante : </b></font>");
				body.append("</td>");
				body.append("<td>");
				body.append("<font color=\"white\"><b>" + uba.getFirstname() + " " + uba.getLastname() +"</b></font>");
				body.append("</td>");
				body.append("</tr>");
				body.append("<tr bgcolor=\"blue\">");
				body.append("<td>");
				body.append("<font color=\"white\"><b>Punteggio : </b></font>");
				body.append("</td>");
				body.append("<td>");
				body.append("<font color=\"white\"><b>" + bs +"</b></font>");
				body.append("</td>");
				body.append("</tr>");
				body.append("</table>");
				body.append("<hr/>");
				GMailSender.sendAsyncMessage("Notifica - Calcetto Score Tracker",body.toString(),u.getEmail());
				logger.info("Notify mail sended to " + u.getUsername());
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	public User getCurrentUser(){
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		UserDetails userDetails = null;
		User currentUser = null;
		if (principal instanceof UserDetails) {
		  userDetails = (UserDetails) principal;
		  String userName = userDetails.getUsername();
		  currentUser = userService.getUser(userName);
		}
		return currentUser;
	}

}
